package org.falak.data;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataBaseHelper extends SQLiteOpenHelper {
	// The Android's default system path of your application database.
	private static String DB_PATH = "/data/data/org.falak.FalakCallerID/databases/";

	private static String DB_NAME = "CallerID_DB";

	private SQLiteDatabase myDataBase;

	private Context myContext = null;

	private String TAG = "DataBaseHelper";

	/**
	 * Constructor Takes and keeps a reference of the passed context in order to
	 * access to the application assets and resources.
	 * 
	 * @param context
	 */
	public DataBaseHelper(Context context) {
		super(context, DB_NAME, null, 1);
		this.myContext = context;
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub

	}

	/**
	 * Creates a empty database on the system and rewrites it with your own
	 * database.
	 * */
	public void createDataBase() throws IOException {
		Log.d(TAG, "createDataBase");

		boolean dbExist = checkDataBase();

		if (dbExist) {
			// do nothing - database already exist
			Log.d(TAG, "createDataBase:DBEXists");

		} else {
			Log.d(TAG, "createDataBase:CreateDB");

			// By calling this method and empty database will be created into
			// the default system path
			// of your application so we are gonna be able to overwrite that
			// database with our database.
			this.getReadableDatabase();

			try {
				Log.d(TAG, "createDataBase:CopyDB");

				copyDataBase();

			} catch (IOException e) {

				Log.d(TAG, "createDataBase:ERROR");

			}
		}

	}

	/**
	 * Check if the database already exist to avoid re-copying the file each
	 * time you open the application.
	 * 
	 * @return true if it exists, false if it doesn't
	 */
	private boolean checkDataBase() {
		Log.d(TAG, "checkDataBase");

		SQLiteDatabase checkDB = null;

		try {
			String myPath = DB_PATH + DB_NAME;
			checkDB = SQLiteDatabase.openDatabase(myPath, null,
					SQLiteDatabase.OPEN_READONLY);

		} catch (SQLiteException e) {

			// database does't exist yet.
			Log.d(TAG, "checkDataBase:NOT FOUND");

		}

		if (checkDB != null) {
			Log.d(TAG, "checkDataBase:FOUND");

			checkDB.close();

		}

		return checkDB != null ? true : false;
	}

	/**
	 * Copies your database from your local assets-folder to the just created
	 * empty database in the system folder, from where it can be accessed and
	 * handled. This is done by transfering bytestream.
	 * */
	private void copyDataBase() throws IOException {
		Log.i(TAG, "copyDataBase");

		// Open your local db as the input stream
		InputStream myInput = myContext.getAssets().open(DB_NAME);

		// Path to the just created empty db
		String outFileName = DB_PATH + DB_NAME;

		// Open the empty db as the output stream
		OutputStream myOutput = new FileOutputStream(outFileName);

		// transfer bytes from the inputfile to the outputfile
		byte[] buffer = new byte[1024];
		int length;
		while ((length = myInput.read(buffer)) > 0) {
			myOutput.write(buffer, 0, length);
		}

		// Close the streams
		myOutput.flush();
		myOutput.close();
		myInput.close();
		Log.i(TAG, "copyDataBase:done");

	}

	public void openDataBase() throws SQLException {
		Log.i(TAG, "openDataBase");

		// Open the database
		String myPath = DB_PATH + DB_NAME;
		myDataBase = SQLiteDatabase.openDatabase(myPath, null,
				SQLiteDatabase.OPEN_READONLY);
		Log.i(TAG, "openDataBase:done");

	}

	@Override
	public synchronized void close() {
		Log.i(TAG, "close");

		if (myDataBase != null) {
			myDataBase.close();
		}

		super.close();

	}

	// Add your public helper methods to access and get content from the
	// database.
	// You could return cursors by doing "return myDataBase.query(....)" so it'd
	// be easy
	// to you to create adapters for your views.

	public boolean checkIsNumberMobile(String code) {
		String sql = "select count(*) as count from mobilenos where code="
				+ code;
		int count = 0;
		if (this.myDataBase == null) {
			this.openDataBase();
		}

		Cursor c = this.myDataBase.rawQuery(sql, null);

		if (c != null) {
			Log.i(TAG, "checkIsNumberMobile:cursorchecked");
			if (c.moveToFirst()) {
				count = c.getInt(0);
				c.close();
			}
		}

		this.close();// DB close
		if (count != 0) {
			return true;
		}
		return false;
	}

	/*
	 * if (c.moveToFirst()) { do { String firstName = c.getString(c
	 * .getColumnIndex("FirstName")); int age =
	 * c.getInt(c.getColumnIndex("Age")); results.add("" + firstName + ",Age: "
	 * + age); } while (c.moveToNext()); } }
	 */

	public String getLocOperator(String code) {
		Log.i(TAG, "getLocOperator");
		String sql = "select c.desc as operator, b.desc as location from "
				+ "mobilenos a, circle b, operator c where a.circle = b.code "
				+ "and a.operator = c.code and a.code = " + code;
		String operator = null;
		String location = null;
		if (this.myDataBase == null) {
			this.openDataBase();
		} else if (this.myDataBase.isOpen()) {
		} else {
			this.openDataBase();
		}

		Cursor c = this.myDataBase.rawQuery(sql, null);

		if (c != null & c.getCount() > 0) {
			Log.i(TAG, "getLocOperator:GOT Something");
			if (c.moveToFirst()) {
				operator = c.getString(0);
				location = c.getString(1);
				c.close();
			}
		}

		this.close();// DB close
		if (operator != null && location != null) {
			return "LOCATION: " + location.toUpperCase() + " \nOPERATOR:  " + operator.toUpperCase();
		}

		return code + ":Mobile operator might be new !";
	}

	public String getIntlLocation(String code) {
		Log.i(TAG, "getIntlLocation");
		String sql = "select country from ISDCode where code=" + code;
		String location = null;
		if (this.myDataBase == null) {
			this.openDataBase();
		} else if (this.myDataBase.isOpen()) {
		} else {
			this.openDataBase();
		}

		Cursor c = this.myDataBase.rawQuery(sql, null);

		if (c != null & c.getCount() > 0) {
			Log.i(TAG, "getIntlLocation:GOT Something");
			if (c.moveToFirst()) {
				location = c.getString(0);
				c.close();
			}
		}

		this.close();// DB close
		if (location != null) {
			return location.toUpperCase();
		}
		return null;
	}

	public String getIndiaLandlineInfo(String phoneNumber) {
		Log.i(TAG, "getIndiaLandlineInfo " + phoneNumber);
		String landlineInfo = null;
		String code = null;
		int codeLength = 2;
		do {
			if (phoneNumber.length() == 13){
				code = phoneNumber.substring(3, 3 + codeLength);
			} else{
				code = phoneNumber.substring(1, 1 + codeLength);
			}

			landlineInfo = landlineLookupDB(code);
			codeLength++;
		} while (landlineInfo == null && codeLength  < 10);
		
		return landlineInfo;
	}

	private String landlineLookupDB(String code) {
		Log.i(TAG, "landlineLookupDB:Code=" + code);
		String sql = "select place, state from STDCode where code=" + code;
		String state = null;
		String location = null;
		if (this.myDataBase == null) {
			this.openDataBase();
		} else if (this.myDataBase.isOpen()) {
		} else {
			this.openDataBase();
		}

		Cursor c = this.myDataBase.rawQuery(sql, null);

		if (c != null & c.getCount() > 0) {
			Log.i(TAG, "landlineLookupDB:GOT Something");
			if (c.moveToFirst()) {
				location = c.getString(0);
				state = c.getString(1);
				c.close();
			}
			return "LOCATION: " + location.toUpperCase() + "\nSTATE: " + state.toUpperCase();
		}

		this.close();// DB close
		return null;
	}
}
